
<template>
	  <div class="tc-adduser-index">
      <section class="add-content">
        <!-- 标题内容 -->
        <section class="title-content">
          <div class="title-box">{{$route.query.type === 'edit' ? '编辑' : '新增'}}用户</div>
        </section>
        <div class="add-content-title">基本信息</div>
        <!-- 表单内容 -->
        <el-form :model="formData" status-icon :rules="rules" ref="formData" label-width="100px" class="demo-formData" @submit.native.prevent>
          <div class="item-box clearfix">
            <el-form-item class="content-box" label="组织名称">
              <el-input v-model="formData.partnerName" disabled></el-input>
            </el-form-item>
            <el-form-item class="content-box" label="账号" prop="userName">
              <el-input v-model="formData.userName"></el-input>
            </el-form-item>
          </div>
          <div class="item-box clearfix">
            <el-form-item class="content-box" label="姓名" prop="nickName">
              <el-input v-model="formData.nickName"></el-input>
            </el-form-item>
            <el-form-item class="content-box" label="部门">
              <!-- <el-input placeholder="请选择内容" :readonly="true" v-model="formData.departmentNmas" class="input-with-select">
                <el-button slot="append" icon="el-icon-more" @click="selectFn('depart')"></el-button>
              </el-input> -->
              <el-cascader
                :show-all-levels="false"
                v-model="formData.deptIds"
                :options="departmentData"
                :props="{ checkStrictly: true, value: 'id', label: 'label', emitPath: false, multiple: true }"
                @change="cascaderChange"
                clearable>
                <template slot-scope="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </div>
          <div class="item-box clearfix">
            <el-form-item class="content-box" label="角色" v-if="formData.systemAccount === 1 || formData.systemAccount === 2">
              <el-input placeholder="请选择内容" disabled v-model="formData.roleNames" class="input-with-select"></el-input>
            </el-form-item>
            <el-form-item class="content-box" label="角色" v-else>
              <el-input placeholder="请选择内容" :readonly="true" v-model="formData.roleNames" class="input-with-select">
                <el-button slot="append" icon="el-icon-more" @click="selectFn('role')"></el-button>
              </el-input>
            </el-form-item>
            <el-form-item class="content-box" label="岗位">
              <el-input placeholder="请选择内容" :readonly="true" v-model="formData.positionNames" class="input-with-select">
                <el-button slot="append" icon="el-icon-more" @click="selectFn('position')"></el-button>
              </el-input>
            </el-form-item>
          </div>
          <div class="item-box clearfix">
            <el-form-item class="content-box" label="小组">
              <el-input placeholder="请选择内容" :readonly="true" v-model="formData.groupNames" class="input-with-select">
                <el-button slot="append" icon="el-icon-more" @click="selectFn('group')"></el-button>
              </el-input>
            </el-form-item>
            <el-form-item class="content-box" label="状态" prop="status">
              <el-select v-model="formData.status" clearable placeholder="启用/停用">
                <el-option label="停用" :value="'1'"></el-option>
                <el-option label="启用" :value="'0'"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="备注：">
            <el-input
              type="textarea"
              :rows="3"
              maxlength="200"
              placeholder="请输入内容"
              v-model="formData.remark">
            </el-input>
          </el-form-item>
        </el-form>
      </section>
      <div class="btm-btn">
        <el-button @click="goBack()">取消</el-button>
        <el-button type="primary" :loading="isBtnLoading" @click="submitForm('formData')">提交</el-button>
      </div>

      <!-- 选择器 -->
      <dialog-select v-if="isShowSelect" :propColse="dialogClose" :propParams="propParams" :propChecked="true"></dialog-select>

      <!-- 树形选择器 -->
      <department-select v-if="isShowTreeSelect" :propColse="dialogTreeClose" :propParams="propParams"></department-select>
    </div>
</template>

<script>
import { mapState,mapMutations } from 'vuex'
import {phone} from '../../../../../static/js/check.js'
import dialogSelect from '@/components/dialogSelect/index'; //选择器
import {addUser, getUserDetail, editUser} from '@/axios/user/user';
import { findPartnerRoleList } from '@/axios/user/role';
import { getDepartmentList } from '@/axios/user/department';
import { optionSelect } from '@/axios/user/team';
import { positionSelect } from '@/axios/user/position';
import departmentSelect from '@/components/departmentSelect/index'; //树形选择器

var validatePhone = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请输入手机号'))
    } else {
      if (!phone.test(value)) {
        callback(new Error('请输入正确的手机号'))
      }
      callback()
    }
  }
export default {
  name: 'username',
  data () {
    return {
      formData: {
        partnerId: [],
        status: '',
        userName: '',
        nickName: '',
        departmentNmas: '',
        deptIds: [],
        roleNames: '',
        roleIds: [],
        groupNames: '',
        groupIds: [],
        positionNames: '',
        postIds: [],
        remark: '',
        systemAccount: ''
      },
      departmentId: '',
      departmentData: [],
      departmentSlect: [],
      roleSlect: [],
      groupSlect: [],
      positionSlect: [],
      isShowSelect: false,
      isShowTreeSelect: false,
      isBtnLoading: false,
      propParams: {
        title: '',
        tableData: [],
        selectData: [],
        tabelHeard: []
      },
      partnerData: {},
      rules: {
        userName: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur', required: true}
        ],
        nickName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        departmentNmas: [
          { required: true, message: '请选择部门', trigger: 'blur' }
        ],
        roleNames: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ],
        groupNames: [
          { required: true, message: '请选择小组', trigger: 'blur' }
        ],
        positionNames: [
          { required: true, message: '请选择岗位', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  computed:{
       ...mapState([
         'editableTabs',
         'editableTabsValue'
       ])
  },
  watch: {
  },
  components: {
    dialogSelect,
    departmentSelect
  },
  mounted() {
  },
  created(){
    this.initData()
  },
  methods: {
      ...mapMutations([
         'SAVE_TOKEN',
         'DETALE_EDITABLETABS',
         'SAVE_EDITABLETABSVALUE'
       ]),
       initData() {
          this.formData.partnerId = this.$route.query.partnerId
          this.formData.partnerName = this.$route.query.partnerName
          if(this.$route.query.type === 'add') {
          } else if (this.$route.query.type === 'edit') {
            getUserDetail({id: this.$route.query.userId}).then((res) => {
              this.formData.userName = res.data.userName
              this.formData.nickName = res.data.nickName
              this.formData.userId = res.data.userId
              this.formData.status = res.data.status
              this.formData.systemAccount = res.data.systemAccount
              this.formData.departmentNmas = res.data.sysDeptList.map((v) => { return v.deptName}).join(',')
              this.formData.deptIds = res.data.sysDeptList.map((v) => { return v.deptId})
              this.formData.roleNames = res.data.sysRoleList.map((v) => { return v.roleName}).join(',')
              this.formData.roleIds = res.data.sysRoleList.map((v) => { return v.roleId})
              this.formData.groupNames = res.data.sysGroupList.map((v) => { return v.groupName}).join(',')
              this.formData.groupIds = res.data.sysGroupList.map((v) => { return v.groupId})
              this.formData.positionNames = res.data.sysPostList.map((v) => { return v.postName}).join(',')
              this.formData.postIds = res.data.sysPostList.map((v) => { return v.postId})
              this.formData.remark = res.data.remark
              // 按钮选择项目
              this.departmentSlect = res.data.sysDeptList.map((v) => { return {name: v.deptName, id: v.deptId}})
              this.roleSlect = res.data.sysRoleList.map((v) => { return {name: v.roleName, id: v.roleId}})
              this.groupSlect = res.data.sysGroupList.map((v) => { return {name: v.groupName, id: v.groupId}})
              this.positionSlect = res.data.sysPostList.map((v) => { return {name: v.postName, id: v.postId}})
            })
          }
          this.getDepartmentData()
       },
      getDepartmentData(){
        getDepartmentList({
           partnerId: this.formData.partnerId
         }).then(res => {
           if (res.code === 200) {
             this.departmentData = res.data
           }
         })
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.$route.query.type === 'add') {
              this.sbmitAdd()
            } else if(this.$route.query.type === 'edit') {
              this.sbmitEdit()
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      sbmitAdd() {
        this.isBtnLoading = true
        var jsonData = {
          userName: this.formData.userName,
          nickName: this.formData.nickName,
          status: this.formData.status,
          partnerId: this.formData.partnerId,
          roleIds: this.formData.roleIds,
          postIds: this.formData.postIds,
          groupIds: this.formData.groupIds,
          deptIds: this.formData.deptIds,
          remark: this.formData.remark
        }
        addUser(jsonData).then((res) => {
          if (res.code === 200) {
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.goBack()
          }
          this.isBtnLoading = false
        })
      },
      sbmitEdit() {
        this.isBtnLoading = true
        var jsonData = {
          userName: this.formData.userName,
          nickName: this.formData.nickName,
          status: this.formData.status,
          partnerId: this.formData.partnerId,
          roleIds: this.formData.roleIds,
          postIds: this.formData.postIds,
          groupIds: this.formData.groupIds,
          deptIds: this.formData.deptIds,
          remark: this.formData.remark,
          userId: this.formData.userId
        }
        editUser(jsonData).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.msg
            })
            this.goBack()
          }
          this.isBtnLoading = false
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      /**
       *  @method 选择部门或者角色
       *  @param {param} param role 角色 depart 部门 group 小组 position 岗位
       */
      selectFn(param) {
        this.propParams.type = param
        this.propParams.tableData = []
        if (param === 'role') {
          this.propParams.title = '角色列表'
          this.propParams.codeValue = 'roleCode'
          this.propParams.tabelHeard = [
            {label: '角色', prop:'name'},
            {label: '角色编码', prop:'roleCode'}
          ]
          findPartnerRoleList({
            partnerId: this.partnerData.id
          }).then(res => {
            if (res.code === 200) {
               this.propParams.tableData = res.data.map((v) => { return {
                  name: v.roleName,
                  roleCode: v.roleCode,
                  id: v.roleId
               }})
               this.propParams.selectData = this.roleSlect
            }
            this.isShowSelect = true
          })
        } else if (param === 'group') {
          this.propParams.title = '小组列表'
          this.propParams.codeValue = 'groupCode'
          this.propParams.tabelHeard = [
            {label: '小组名称', prop:'name'},
            {label: '小组编码', prop:'groupCode'}
          ]
          optionSelect({
            partnerId: this.partnerData.id
          }).then(res => {
            if (res.code === 200) {
              this.propParams.tableData = res.data.map((v) => { return {
                name: v.groupName,
                groupCode: v.groupCode,
                id: v.groupId
              }})
              this.propParams.selectData = this.groupSlect
            }
            this.isShowSelect = true
          })
        } else if (param === 'position') {
          this.propParams.title = '岗位列表'
          this.propParams.codeValue = 'postCode'
          this.propParams.tabelHeard = [
            {label: '岗位名称', prop:'name'},
            {label: '岗位编码', prop:'postCode'}
          ]
          positionSelect({
            partnerId: this.partnerData.partnerId
          }).then(res => {
            if (res.code === 200) {
              this.propParams.tableData = res.data.map((v) => { return {
                name: v.postName,
                postCode: v.postCode,
                id: v.postId
              }})
              this.propParams.selectData = this.positionSlect
            }
            this.isShowSelect = true
          })
        }
      },
      /**
       *  @method 关闭选择器
       */
      dialogClose(val, type) {
        if (val) {
          var listIds = val.map( (v,i) => {
            return v.id
          })
          if (type === 'depart') {
            this.formData.departmentNmas = val.map( (v,i) => {
              return v.name
            }).join(',')
            this.formData.deptIds = listIds
            this.departmentSlect = val
          } else if (type === 'role') {
            this.formData.roleNames = val.map( (v,i) => {
              return v.name
            }).join(',')
            this.formData.roleIds = listIds
            this.roleSlect = val
          } else if (type === 'group') {
            this.formData.groupNames = val.map( (v,i) => {
              return v.name
            }).join(',')
            this.formData.groupIds = listIds
            this.groupSlect = val
          } else if (type === 'position') {
            this.formData.positionNames = val.map( (v,i) => {
              return v.name
            }).join(',')
            this.formData.postIds = listIds
            this.positionSlect = val
          }
        }
        this.isShowSelect = false
      },
      cascaderChange(v) {
        this.formData.deptIds = v
        // if (v) {
        //   this.formData.deptIds.push(v)
        // }
      },
      /**
       * @method 返回
       */
      goBack() {
        this.$router.push({
          path: '/system/user/manage',
          query: {
            pageNum: this.$route.query.pageNum
          }
        })
      }
  }
};
</script>

<style lang="scss">
@import "./index.scss";
</style>